/*******************************************************************************
 * Copyright (c) 2011 Gijs de Vries aka Janoz.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Gijs de Vries aka Janoz - initial API and implementation
 ******************************************************************************/
/* COPYRIGHT (C) 2008 Gijs de Vries. All Rights Reserved. */
package com.janoz.httpd.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

import com.janoz.httpd.MimeType;
import com.janoz.httpd.RequestHandler;
import com.janoz.httpd.Response;
import com.janoz.httpd.StatusCode;

/**
 * An implementation of the request handler to serve a file
 * directory tree placed within a jar file. 
 * 
 * @author Gijs de Vries
 *
 */
public class JarFileHandler implements RequestHandler {

	private static final int BUFF_SIZE = 1024;

	private JarFile jarFile;
	private String root;
	
	/**
	 * 
	 * @param jarFile the jarfile from which the files will be served
	 * @param root the directory within the jarfile that will function as root
	 */
	public JarFileHandler(JarFile jarFile, String root) {
		this.jarFile = jarFile;
		this.root = root;
	}

	/**
	 * @see com.janoz.httpd.RequestHandler#handleRequest(String, Properties)
	 * @param uri the uri of the request
	 * @param params the get parameters of the request
	 * @return The generated response that will be sent to the client
	 */
	public Response handleRequest(String uri, Properties params) {
		if (jarFile == null) {
			System.err.println("JarFile undefined.");
			return Response.createEncodingSave(StatusCode.INTERNALERROR);
		}
		ZipEntry entry = jarFile.getEntry(root + uri);
		if (entry == null) {
			return Response.createEncodingSave(StatusCode.NOTFOUND);
		}
		try {
			int dotPos = uri.lastIndexOf('.');
			String ext = "";
			if (dotPos > 0) {
				ext = uri.substring(dotPos+1);
			}
			return new Response(readFile(jarFile.getInputStream(entry)), 
					MimeType.getMimeType(ext));
			
		} catch (IOException e) {
			System.err.println("Error reading file " 
					+ entry.getName() + " from " 
					+ jarFile.getName() + ".");
			return Response.createEncodingSave(StatusCode.INTERNALERROR);
		}
	}

	private byte[] readFile(InputStream input) throws IOException {
		ByteArrayOutputStream result = new ByteArrayOutputStream();
		
        byte[] buffer = new byte[BUFF_SIZE];
        int n;
        while (-1 != (n = input.read(buffer))) {
            result.write(buffer, 0, n);
        }
        return result.toByteArray(); 
	}

}
